package cn.leestudio.restlib;

import android.content.Context;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import cn.leestudio.restlib.core.AbsCall;

/**
 * 描 述:
 *
 * @author: lihui
 * @date: 2017-10-20 15:43
 */

public class Rest<C extends AbsCall,S> {

    public S create(final Context context, final Class<C> restCall, Class<S> service){
        return (S) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
                new InvocationHandler() {

                    @Override public Object invoke(Object proxy, Method method, Object... args)
                            throws Throwable {
                        if (method.getDeclaringClass() == Object.class) {
                            return method.invoke(this, args);
                        }
                        return request(context,restCall,method,args);
                    }
                });
    }

    private Object request(Context context,Class<C> restCall,Method method,Object... args){
        AbsCall call = null;
        try {
            call = restCall.newInstance();
            call.init(context,method,args);
            call.exec();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return call;
    }

}
